package com.yupi.springbootinit.service.impl;


import com.baidubce.appbuilder.base.exception.AppBuilderServerException;
import com.baidubce.appbuilder.console.appbuilderclient.AppBuilderClient;
import com.baidubce.appbuilder.model.appbuilderclient.AppBuilderClientIterator;
import com.baidubce.appbuilder.model.appbuilderclient.AppBuilderClientResult;
import com.baidubce.qianfan.Qianfan;
import com.baidubce.qianfan.model.chat.ChatResponse;
import com.yupi.springbootinit.model.dto.ai.AiResponse;
import okhttp3.*;
import org.springframework.stereotype.Component;

import java.io.IOException;

import static com.yupi.springbootinit.constant.AiConstant.QIANFAN_ACCESS_KEY;
import static com.yupi.springbootinit.constant.AiConstant.QIANFAN_SECRET_KEY;


/**
 * 百度ai调用
 * Acc:ALTAKOj4fLS96uSXXJSlk5PSpZ
 * sec:713b9cff96ad43ffb349ad611bddbc21
 */
@Component
public class BaiDuAiManager {
    /*public static String  AiChart(String content) {
        Qianfan qianfan = new Qianfan(QIANFAN_ACCESS_KEY, QIANFAN_SECRET_KEY);
        AiResponse aiResponse = new AiResponse();
        ChatResponse response = qianfan.chatCompletion()
                .model("ERNIE-Speed-8K")
                .addMessage("user", content)
                .temperature(0.75)
                .responseFormat("conclusion:{},option:{}")
                .execute();
        String result = response.getResult();
        // 提取 option 部分
        //String optionPart = result.split("option:\\n\\n\\n```javascript\\n")[1].split("\\n```")[0].replace("option = ", "").trim();

        // 提取 conclusion 部分
        //String conclusionPart = result.split("conclusion:\\n\\n")[1].trim();

        //aiResponse.setChartOption(optionPart);
        //aiResponse.setChartConclusion(conclusionPart);

        return result;
    }*/


    public static String BaiDuAiChart(String content) throws IOException, AppBuilderServerException {
        // 设置环境中的TOKEN，以下TOKEN请替换为您的个人TOKEN，个人TOKEN可通过该页面【获取鉴权参数】或控制台页【密钥管理】处获取
        System.setProperty("APPBUILDER_TOKEN", "bce-v3/ALTAK-6Zg8ToKnF4l7UR6WUF5HG/dba460dfd0cefe61b269b2e1059862cf79d06df8");
        // 从AppBuilder控制台【个人空间】-【应用】网页获取已发布应用的ID
        String appId = "29eac309-f7a2-48d0-85ff-4ceec7aae3f3";
        AppBuilderClient builder = new AppBuilderClient(appId);
        String conversationId = builder.createConversation();

        AppBuilderClientIterator itor = builder.run(content, conversationId, new String[] {}, false);
        StringBuilder answer = new StringBuilder();
        while (itor.hasNext()) {
            AppBuilderClientResult response = itor.next();
            answer.append(response.getAnswer());
        }
        return answer.toString();
    }
}
